package cool.taomu.toolkit.rpc.thrift.provider

import com.google.inject.Provider
import org.apache.thrift.transport.TTransport
import org.slf4j.LoggerFactory
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import com.google.inject.Inject
import com.google.inject.name.Named
import java.time.Duration

class TTransportPoolProvider implements Provider<GenericObjectPoolConfig<TTransport>> {
    val static LOG = LoggerFactory.getLogger(TTransportPoolProvider);

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.maxTotal")
    int maxTotal = 30

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.minIdle")
    int minIdle = 10

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.maxIdle")
    int maxIdle = 20
    
    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.maxWait")
    long maxWait = 1

    override get() {
        LOG.info("创建连接池")
        var config = new GenericObjectPoolConfig<TTransport>();
        config.setMaxTotal(maxTotal); // 最大连接数
        config.setMinIdle(minIdle); // 最小空闲连接数
        config.setMaxIdle(maxIdle); // 最大空闲连接数
        config.setMaxWait(Duration.ofSeconds(maxWait));
        // 启用连接验证
        //config.setTestOnBorrow(true); // 借用对象时验证
        config.setTestWhileIdle(true); // 空闲时验证
        config.setTestOnReturn(true);

        // 设置每 60 秒运行一次空闲连接回收任务
        config.setTimeBetweenEvictionRuns(Duration.ofSeconds(60));
       // config.setMinEvictableIdleTime(Duration.ofMinutes(1));
        //config.setSoftMinEvictableIdleTime(Duration.ofMinutes(30));
        return config;
    }
}
